package cn.feizhu.aimarket.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.feizhu.aimarket.common.BaseResponse;
import cn.feizhu.aimarket.common.ResultUtils;
import cn.feizhu.aimarket.model.dto.user.UserLoginRequest;
import cn.feizhu.aimarket.model.vo.BookVO;
import cn.feizhu.aimarket.model.vo.UserVO;
import cn.feizhu.aimarket.service.UserService;
import cn.feizhu.aimarket.ratelimit.annotation.RateLimit;
import cn.feizhu.aimarket.ratelimit.enums.RateLimitType;
import java.util.concurrent.TimeUnit;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {


    @Resource
    private UserService userService;

    @SaIgnore
    @RateLimit(key = "user.login", limitType = RateLimitType.IP, rate = 5, rateInterval = 1, timeUnit = TimeUnit.MINUTES, message = "登录频率过高，请稍后再试")
    @PostMapping("user/login")
    public BaseResponse<SaTokenInfo> login(@RequestBody UserLoginRequest userLoginRequest) {
        Long userId = userService.login(userLoginRequest);
        StpUtil.login(userId);
        StpUtil.getSession().set("userId", userId);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return ResultUtils.success(tokenInfo);
    }

    @SaCheckLogin
    @RateLimit(key = "user.islogin", limitType = RateLimitType.USER, rate = 60, rateInterval = 1, timeUnit = TimeUnit.MINUTES, message = "请求过于频繁，请稍后再试")
    @GetMapping("/user/islogin")
    public BaseResponse<Long> isLogin() {
        StpUtil.checkLogin();
        return ResultUtils.success(StpUtil.getLoginIdAsLong());
    }

    @SaCheckLogin
    @RateLimit(key = "user.getloginuser", limitType = RateLimitType.USER, rate = 60, rateInterval = 1, timeUnit = TimeUnit.MINUTES, message = "请求过于频繁，请稍后再试")
    @GetMapping("/user/getloginuser")
    public BaseResponse<UserVO> getUserInfo() {
        long userId = (long) StpUtil.getSession().get("userId");
        UserVO userVO = userService.getUserInfo(userId);
        return ResultUtils.success(userVO);
    }



    /**
     * 根据是否传入应用ID才采用是全部查询还是查询特定书籍
     * @param appId
     */
    @SaCheckLogin
    @RateLimit(key = "user.mybooks", limitType = RateLimitType.USER, rate = 30, rateInterval = 1, timeUnit = TimeUnit.MINUTES, message = "请求过于频繁，请稍后再试")
    @GetMapping("/user/mybooks")
    public BaseResponse<List<BookVO>> listMyBooks(@RequestParam(required = false) Long appId) {
        // 这里获取userId
        long userId = StpUtil.getLoginIdAsLong();
        List<BookVO> myBooks = userService.listMyBooks(userId,appId);
        return ResultUtils.success(myBooks);
    }

}
